<template>
  <div>
    <!-- 面包屑 -->
    <bread></bread>
    <!-- 添加角色区域 -->
    <el-card>
      <el-row>
        <el-card>
          <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
        </el-card>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="list" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,i1) in scope.row.children"
              :class="['bdbottom',i1 === 0  ? 'bdtop' : '','vcenter']"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级三级 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :class="[i2 === 0  ? '' : 'bdtop','vcenter']"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3,i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="edit(scope.row.id)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="delDialogVisible(scope.row.id)"
            >>删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialong(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加区域 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addRuleForms">
        <!-- 输入区域 -->
        <el-form
          :model="addForm"
          :rules="rules"
          ref="addRuleForm"
          label-width="8/0px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addFormList">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改区域 -->
      <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editRuleForms">
        <!-- 输入区域 -->
        <el-form
          :model="editForm"
          :rules="rules"
          ref="editRuleForm"
          label-width="8/0px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editFormList">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限 -->
      <el-dialog title="分配权限" :visible.sync="treeDialogVisible" width="50%"
      @close="setRightDialongClosed">
        <!-- 树形控件 -->
        <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key='id' 
        default-expand-all :default-checked-keys="defkeys" ref="treeRef"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="treeDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import bread from "../bread";
import API from "../API/Api";
export default {
  name: "",
  data() {
    return {
      list: [],
      addDialogVisible: false,
      addForm: {
        roleName: "",
        roleDesc: ""
      },
      // 添加的校验
      rules: {
        roleName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ]
      },
      editForm: {},
      editDialogVisible: false,
      // 删除的校验
      rules: {
        roleName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ]
      },
      treeDialogVisible: false,
      rightsList: [],
      treeProps: {
        label: "authName",
        children: "children"
      },
      defkeys:[],
      roleId:''
    };
  },
  mounted() {
    this.getLists();
  },
  methods: {
    // 渲染数据
    getLists() {
      API.getLists().then(res => {
        if (res.meta.status !== 200) {
          return this.$message.error("获取角色列表失败");
        }
        this.list = res.data;
        // console.log(this.list);
      });
    },
    // 删除每一项
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该内容, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("取消删除");
      }
      API
        .removeRightById(role.id,rightId)
        .then(res => {
          console.log(res);
          if (res.meta.status !== 200) {
            return this.$message.error("删除权限失败");
          }
          role.children = res.data;
        });
    },
    // 添加
    async addFormList() {
      this.$refs["addRuleForm"].validate(valid => {
        if (valid) {
          API.addFormList(this.addForm).then(res => {
            if (res.meta.status != 201) {
              this.$message.error("创建失败");
            }
            this.$message.success("创建成功");
            this.addDialogVisible = false;
            this.getLists();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    addRuleForms() {
      this.$refs.addRuleForm.resetFields();
    },
    // 修改对话框
    edit(id) {
      this.editDialogVisible = true;
      API.edit(id).then(res => {
        if (res.meta.status !== 200) {
          this.$message.error("获取失败");
        }
        console.log(res);
        this.editForm = res.data;
      });
    },
    // 修改数据
    async editFormList() {
      this.$refs["editRuleForm"].validate(valid => {
        if (valid) {
         API
            .editFormList(this.editForm.roleId, this.editForm)
            .then(res => {
              console.log(res);
              if (res.meta.status != 200) {
                return this.$message.error("修改失败");
              }
              this.$message.success("修改成功");
              this.editDialogVisible = false;
              this.getLists();
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    editRuleForms() {
      this.$refs.editRuleForm.resetFields();
    },
    // 删除数据
    async delDialogVisible(id) {
      var confrim = await this.$confirm(
        "此操作将永久删除该数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      console.log(confrim);
      if (confrim !== "confirm") {
        return this.$message.error("取消删除");
      }
      API.delDialogVisible(id).then(res => {
        if (res.meta.status !== 200) {
          return this.$message.error("删除失败");
        }
        this.$message.success("删除成功");
        this.getLists();
      });
    },
    showSetRightDialong(role) {
      this.roleId=role.id
      API.showSetRightDialong().then(res => {
        console.log(res);

        if (res.meta.status !== 200) {
          return this.$message.error("获取权限数据失败");
        }
        this.rightsList = res.data;
         this.getLeafKeys(role,this.defkeys);
        this.treeDialogVisible = true;
      });
    },
    // 权限管理
    getLeafKeys(node,arr){
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item=>{
        this.getLeafKeys(item,arr)
      })
    },
    setRightDialongClosed(){
      this.defkeys = []
    },
    // 点击分配权限
    allotRights(){
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys(),
        ]
        console.log(keys);
        const idStr = keys.join(',')
        // 分配权限
        API.allotRights(this.roleId,idStr).then(res=>{
          if(res.meta.status !==200){
            return this.$message.error('分配权限失败')
          }
          this.$message.success('分配权限成功')
          this.getLists()
           this.treeDialogVisible = false
        })
    }
  },
  computed: {},
  components: {
    bread
  },
  watch: {},
  getters: {}
};
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>